use warnings;
use strict;

sub DCImdbApi {
	my ($tt, $title, $year, $edit, $re) = @_ ;
	my $record = '';
	my $errors = '';
	
	# fix lookup needs separate title and year
	#my $year='';
	# $title may not include year
	my $short_title = $title; 
	# if it does
	if ($title =~ m!^(.+) (\d{4})$!){ $short_title = $1; unless ($year){ $year = $2; } }
	
	
	# check for existing record - always needed in case no incomming tt
	open (RDB, "<$VAR{'DataDir'}/ppweb_dcimdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_dcimdb.txt, $! (LI01)", 1, 0);
	while (<RDB>){
		if ($tt and m!^$tt [^\t]+\t(.+)!){
			$record = "$1\n";
			&Print ("Got DC IMDb API record (cached): $title (LI02)", 4, 0);
			last;
		}
		# allow for listing title w/ or w/o year
		elsif ($title and m!^(tt\d+) $title(?:[^\t]+)?\t(.+)!){
			$tt = $1;
			$record = "$2\n";
			&Print ("Got DC IMDb API record (cached): $title (LI02)", 4, 0);
			last;
		}
	}
	close RDB or warn $!;
	
	# get new or updated record
	if (!$record or $edit eq 'up'){ # don't enter if edit eq del or fix
		#&Print ("Fetching DC IMDb API record: $title (LI02)", 5, 0);
		require LWP::UserAgent;
		my $user_agent = LWP::UserAgent->new;
		$user_agent->agent("Mozilla/8.1");
		my $url;
		if ($tt){ $url = "http://deanclatworthy.com/imdb/?id=$tt&type=text"; }
		elsif ($short_title and $year){ $url = "http://deanclatworthy.com/imdb/?q=$short_title&year=$year&type=text"; }
		# imdbapi doesn't provide multiple returns, not using
		#else { $url = "http://imdbapi.com/?t=$short_title&plot=full&tomatoes=true"; }
		#my $image_url;
		my $response = $user_agent->get($url);
		if ($response->is_success and $response->decoded_content) {
			my ($lang, $genre, $run, $rate, $votes) = ('') x 5;
			if ($response->decoded_content =~ m!imdbid\|(tt\d{7})\n!){ $tt = $1; }
			if ($response->decoded_content =~ m!rating\|Ratings:\s([\d.]+)!){ $rate = $1; }
			if ($response->decoded_content =~ m!rating\|([\d.]+)\n!){ $rate = $1; }
			if ($response->decoded_content =~ m!votes\|(\d+)\n!){ $votes = $1; }
			if ($response->decoded_content =~ m!genres\|([^\n]+)\n!){ $genre = $1; }
			if ($response->decoded_content =~ m!languages\|([^\n]+)\n!){ $lang = $1; }
			if ($response->decoded_content =~ m!runtime\|(?:\w+:)?(\d+min)!){ $run = $1; }
			
			if ($response->decoded_content =~ m!Exceeded API usage limit!){
				&Print ('DC IMDb API usage limit (30 requests per hour) exceeded (TM20)', 1, 0);
				$record = '';
			}
			elsif ($response->decoded_content =~ m!error\|Film not found$!){
				&Print ('Film not found at DC IMDb API (TM20)', 2, 0);
				$record = 'nf';
			}
			else { 
				&Print ('DC IMDb API record fetch successful for: '.$title.' (TM20)', 4, 0);
				$record = "$tt $title\t$rate ($votes)  $genre  $run  $lang\n";
				if ($edit eq 'up'){
					local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_dcimdb.txt");
					while(<>){
						if ($. == 1) { 
							print $record;
							unless (m!^$tt!){ print; } # replaced record on 1st line
						}
						elsif (m!^$tt!){ next; } # replaced record elsewhere
						else { print; }
					}
				}
				else {
					open (WDB, ">>$VAR{'DataDir'}/ppweb_dcimdb.txt") or &Print ("  Couldn't open $VAR{'DataDir'}/ppweb_dcimdb.txt, $! (TM21)", 1, 0);
						print WDB $record;
					close WDB or warn $!;
				}
				$record =~ s!^$tt $title\t!!; # remove leading id
			}
			#$record = "<A HREF=\"http://www.imdb.com/title/$tt/\">IMDb:</A>  $record"; # add IMDb label/link
			#if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
			
# 			$record = ''; # clear old record for updating
# 			my $json = $response->decoded_content;
# 			my $plot;
# 			$json =~ s![{}]!!g;
			# my %ash=split /,|=/, $str; # split is or
# 			my %dc =  split(/[|\n]/, $response->decoded_content;
# 			if ($dc{title})
# 			foreach my $k (keys %values) {
# 			print "$k: $values{$k}\n";
# 			}
# # 			while ($rec){
# # 				chomp;
# # 				my ($key, $val) = split /|/;
# # 				$hash{$key} .= exists $hash{$key} ? ",$val" : $val;
# # 			}
# 			while ($response->decoded_content =~ m!\n!
			#my @rec = split (/\n/, $response->decoded_content);
			#my ($dctitle, $year, $lang, $country, $genre, $run, $rate, $votes, $tturl) = ('') x 9;
# 			foreach (@rec){
# 				s!^title|!Title.....: !;
# 				s!^year|!Year......: !;
# 				s!^rating|!Rated.....: !;
# 				s!^votes|!Votes.....: !;
# 				s!^genres|!Genre.....: !;
# 				s!^languages|!Language..: !;
# 				s!^country|!Country...: !;
# 				s!^usascreens|!US screens: !;
# 				s!^runtime|!Runtime...: !;
# 				if (s!^imdbid|(.+)$!!){ $tt=$1; next; }
# 				elsif (s!^imdburl|(.+)$!!){ $tturl=$1; next; }
# 				elsif (s!^series|1$!!){ $tv=1; next; }
# 				$record .= "$_<br>\t";
# 			}
# 			foreach (@rec){
# 				if (m!^title\|(.*)!){ $dctitle = "Title.....: $1<br>\t"; }
# 				elsif (m!^year\|(.*)!){ $year = "Year......: $1<br>\t"; }
# 				elsif (m!^rating\|(.*)!){ $rate = $1; }
# 				#elsif (m!^rating\|(.*)!){ $rate = "Rated.....: $1<br>\t"; }
# 				#elsif (m!^votes\|(.*)!){ $votes = "Votes.....: $1<br>\t"; }
# 				elsif (m!^votes\|(.*)!){ $votes = $1; }
# 				#elsif (m!^genres\|(.*)!){ $genre = "Genre.....: $1<br>\t"; }
# 				elsif (m!^genres\|(.*)!){ $genre = $1; }
# 				#elsif (m!^languages\|(.*)!){ $lang = "Language..: $1<br>\t"; }
# 				elsif (m!^languages\|(.*)!){ $lang = $1; }
# 				elsif (m!^country\|(.*)!){ $country = "Country...: $1<br>\t"; }
# 				#elsif (m!^usascreens\|(.*)!){ $screens = "US screens: $1<br>\t"; }
# 				#elsif (m!^runtime\|(.*)!){ $run = "Runtime...: $1<br>\t"; }
# 				elsif (m!^runtime\|(.*)!){ $run = $1; }
# 				elsif (m!^imdbid\|(.+)!){ unless($tt){$tt=$1;} }
# 				elsif (m!^imdburl\|(.+)!){ $tturl=$1; }
# 				#elsif (m!^series\|1!){ $tv=1;}
# 			}
# 			$record = "$tt $title\t$rate/$votes  $genre  $run  $lang\n";
			#$record = "$tt $title\t$dctitle$year$lang$country$genre$run$rate$votes$DateTime[2]\n";
			#unless ($record =~ m!"Response":"Parse Error"!){
# 				local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_dcimdb.txt");
# 				while(<>){
# 					if ($. == 1) { 
# 						print $record; # new and updated records
# 						unless (m!^$tt!){ print; } # replaced record on 1st line
# 					}
# 					elsif (m!^$tt!){ next; } # replaced record elsewhere
# 					else { print; }
# 				}
# 				$record =~ s!^$tt $title\t!!; # remove leading id
# 				if ($edit eq 'up'){ $record = "Record Updated\n\n$record"; }
			#}
		}
		else { 
			&Print ('DC IMDb API record fetch failed: '.$response->status_line.' (LI03)', 1, 0); 
			$errors .= 'DC IMDb API record fetch failed: '.$response->status_line."\n";
		}
		
# 		# fetch image, if we don't have one
# 		if ($image_url and !-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
# 			&Print ("Fetching IMDb image for: $title (LI02)", 5, 0);
# 			if ($image_url =~ m!jpg$!){
# 				$response = $user_agent->get($image_url, ':content_file' => "$VAR{'PPWebDir'}/images/$tt.jpg");
# 				unless ($response->is_success) {
# 					&Print ('IMDb image fetch failed: '.$response->status_line.' (LI04)', 1, 0);
# 					$errors .= 'IMDb image fetch failed: '.$response->status_line."\n";
# 				}
# 			}
# 			# to let me know if not all images are .jpg
# 			else { &Print ("Image not a jpg: $image_url (LI05)", 1, 0); }
# 		}
	}

	# process record
	if ($edit eq 'del'){ 
		&Print ("Deleting DC IMDb API record: $title (LI06)", 4, 0);
		local ($^I, @ARGV) = ('.bak', "$VAR{'DataDir'}/ppweb_dcimdb.txt");
		while(<>){
			unless (m!^$tt!){ print; } 
		}
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Record Deleted</font></pre></td></tr><tr><td>";
		return $record;
	}
	elsif ($edit eq 'sr'){ 
		if ($record eq 'nf'){
			if ($re =~ m!(.+):(\d+)!){ 
				$a = $2;
				local ($^I, @ARGV) = ('.bak', "$VAR{'HtmlDir'}/$1.html");
				while(<>){
					s!^(<P><A NAME="$a".+)>IMDb search<!$1>not in IMDb<!;
					print;
				}
			}
			$record = '';
		}
		elsif ($record){
			$record = "<A HREF=\"http://www.imdb.com/title/$tt/\">IMDb:</A>  $record"; 
			chomp $record;
			$record =~ s!  !&nbsp;&nbsp;&nbsp;!g;
			if ($re =~ m!(.+):(\d+)!){ 
				$a = $2;
				local ($^I, @ARGV) = ('.bak', "$VAR{'HtmlDir'}/$1.html");
				while(<>){
					s!^(<P><A NAME="$a".+)<br>Details!$1<br>$record<br>Details!;
					print;
				}
			}
		}
	}
	elsif ($record){
		$record = "<A HREF=\"http://www.imdb.com/title/$tt/\">IMDb:</A>  $record";
		# replace all tabs and <br>'s with newline
		#$record =~ s!<br>\t?!\n!g;
		# add pre container and image - if one exists, and td/tr close/start
		if (-e "$VAR{'PPWebDir'}/images/$tt.jpg"){
			$record = "<img SRC=\"$VAR{'PPWebUrl'}/images/$tt.jpg\" style=\"float:right\; padding-right:50px;\">\n<pre><font face=\"Monospace,Courier,Courier New\">$record\n</font></pre><br clear=\"all\"></td></tr><tr><td>\n";
		}
		elsif ($record =~ m!"Response":"Parse Error"!){
			$record = "<pre><font face=\"Monospace,Courier,Courier New\">The IMDb API site returned a 'Parse Error', try again later.</font></pre></td></tr><tr><td>";
		}
		else { $record = "<pre><font face=\"Monospace,Courier,Courier New\">$record</font></pre></td></tr><tr><td>"; }
		return $record;
	}
	else { 
		$record = "<pre><font face=\"Monospace,Courier,Courier New\">Unable to fetch record\n$errors</font></pre></td></tr><tr><td>";
		return $record;
	}
}

1;